package com.elinkway.infinitemovies.ui.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.listener.MyTencentLocationListener;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.bean.LoginDataRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.MyLocationManager;
import com.elinkway.infinitemovies.utils.StringUtil;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.Utils;
import com.elinkway.infinitemovies.view.PagerSlidingTabStrip;
import com.le123.ysdq.R;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhaopeipei on 2016/6/28.
 */
public abstract class BaseActionBarActivity extends BaseActivity {

    public static final String TAG = "HomeBackReceiver";
    public static final String SYSTEM_REASON = "reason";
    public static final String SYSTEM_HOME_KEY = "homekey";
    public static final String SYSTEM_HOME_KEY_LONG = "recentapps";

    private String mClassName;
    protected String currentPageId;
    protected Map<String, String> dbPgvMap;

    private HomeBackReceiver mHomeKeyReceiver = null;

    public ActionBar mActionBar;
    protected RelativeLayout mActionView;
    protected ImageView mLeftBackIv;
    protected ImageView mRightFirstIv;
    protected ImageView mRightSecondIv;
    public TextView mRightFirstTv;
    protected RelativeLayout mSearchKeywordTv;
    protected TextView mTitleTv;
    protected View mRedIconView;
    protected PagerSlidingTabStrip mUtilsTabs;
    public boolean isToBackGround = false;
    public boolean isBackToForeGround = false;
    protected Activity mCurActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerHomeKeyReceiver(this);
        mCurActivity = this;
    }

    protected void initActionBar() {
        mActionBar = getSupportActionBar();
        mActionBar.setDisplayShowCustomEnabled(true);
        mActionBar.setDisplayHomeAsUpEnabled(false);
        mActionBar.setDisplayShowHomeEnabled(false);
        mActionBar.setDisplayShowTitleEnabled(false);
        mActionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
        View mCustomView = getLayoutInflater().inflate(R.layout.new_actionbar_layout, null);
        mUtilsTabs = (PagerSlidingTabStrip) mCustomView.findViewById(R.id.utils_tabs);
        mActionView = (RelativeLayout) mCustomView.findViewById(R.id.new_action_layout);
        mRightFirstIv = (ImageView) mCustomView.findViewById(R.id.right_first_iv);
        mRightSecondIv = (ImageView) mCustomView.findViewById(R.id.right_second_iv);
        mLeftBackIv = (ImageView) mCustomView.findViewById(R.id.left_back_iv);
        mRightFirstTv = (TextView) mCustomView.findViewById(R.id.right_first_tv);
        mTitleTv = (TextView) mCustomView.findViewById(R.id.title_tv);
        mRedIconView = mCustomView.findViewById(R.id.red_icon_view);
        mSearchKeywordTv = (RelativeLayout) mCustomView.findViewById(R.id.search_keyword);
        mLeftBackIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!StringUtil.isEmpty(mClassName) && mClassName.equals(LoginActivity.TAG)) {
                    LoginDataRecord loginDataRecord = MyDataRecordCreater.build(LoginDataRecord.class);
                    loginDataRecord.setCur_url("page_login");
                    loginDataRecord.setRef_url("page_uc");
                    loginDataRecord.setAcode("0");
                    loginDataRecord.setAction("login_back_btn");
                    RealmDaoManager.addMyDataRecord(loginDataRecord);
                }
                MoviesApplication.getInstance().startMainFromPushBack(mCurActivity, null);

                finish();
            }
        });
        mActionBar.setCustomView(mCustomView, new ActionBar.LayoutParams(
                ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT));
        ViewParent viewParent = mCustomView.getParent();
        if (viewParent instanceof Toolbar) {
            ((Toolbar) viewParent).setContentInsetsAbsolute(0, 0);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MoviesApplication.getInstance().setTopActivity(BaseActionBarActivity.this);
        postUmengVisitEvent();
        postBDPageShow();
        if (!TextUtils.isEmpty(mClassName)) {
            setCurrentClassName(mClassName);
        }
        //重新定位
        if(MoviesApplication.getInstance().isNeedReLocation()){
            MoviesApplication.getInstance().setNeedReLocation(false);
            new MyLocationManager(this, new MyTencentLocationListener(){

                @Override
                public void onLocationSuccese(String cityInfo) {

                }

                @Override
                public void onLocationTimeOut() {

                }
            });
        }

        if (isToBackGround) {
            isToBackGround = false;
            isBackToForeGround = true;
        }
    }

    @Override
    protected void onPause() {
        MoviesApplication.getInstance().setmPgvLastPageId(currentPageId);
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (!Utils.isAppOnForeground(getApplicationContext())) {
            isToBackGround = true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterHomeKeyReceiver(this);
    }

    public void setActionBarActivityClassName(String className) {
        mClassName = className;
    }

    public void postBDPageShow(){
        if(!TextUtils.isEmpty(currentPageId)){
            if(!currentPageId.startsWith("home_")){
                if(dbPgvMap == null) {
                    dbPgvMap = new HashMap<String, String>();
                }
                dbPgvMap.put("ref", MoviesApplication.getInstance().getmPgvLastPageId());
                BigDataApi.bigDataPageShowReport(currentPageId, dbPgvMap, this);
            }
        }
    }

    public void postUmengVisitEvent() {
        if (DownloadActivity.TAG.equals(mClassName)) {
            UmengEventPoster.postPageVisitTime(UmengEventPoster.VISIT_DOWNLOAD,
                    MoviesApplication.getInstance().getLastPageClassName());
        } else if (VideoDetailActivity.TAG.equals(mClassName) || TopicDetailActivity.TAG.equals(mClassName)) {
            dealWithVisitUmeng();
        }

    }

    public void postUmengLeaveEvent() {
        if (ChannelDetailActivity.TAG.equals(mClassName)) {
            dealWithUmeng();
        } else if (NewMainActivity.TAG.equals(mClassName)) {
            dealWithUmeng();
        } else if (FavoriteActivity.TAG.equals(mClassName)) {
            UmengEventPoster.postPageLeaveTime(UmengEventPoster.LEAVE_FAVORITE);
        } else if (PlayHistoryActivity.TAG.equals(mClassName)) {
            UmengEventPoster.postPageLeaveTime(UmengEventPoster.LEAVE_HISTORY);
        } else if (DownloadActivity.TAG.equals(mClassName)) {
            UmengEventPoster.postPageLeaveTime(UmengEventPoster.LEAVE_DOWNLOAD);
        } else if (VideoDetailActivity.TAG.equals(mClassName)) {
            UmengEventPoster.postPageLeaveTime(UmengEventPoster.LEAVE_VIDEO_DETAIL);
        }
    }

    public void setCurrentClassName(String childFragmentName) {
        MoviesApplication.getInstance().setLastPageClassName(childFragmentName);
    }

    public class HomeBackReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (TextUtils.isEmpty(mClassName)) {
                return;
            }
            LogUtils.d(TAG, "onReceive " + mClassName);
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_REASON);
                if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
                    //表示按了home键,程序到了后台
                    LogUtils.e(TAG, "out of the application");
                    MoviesConstant.isFirstIn4GPlayVideo = true;
                    MoviesApplication.getInstance().setNeedReLocation(true);
                    postUmengLeaveEvent();
                } else if (TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)) {
                    //表示长按home键,显示最近使用的程序列表
                }
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                MoviesApplication.getInstance().startMainFromPushBack(mCurActivity, null);
        }
        return super.onKeyDown(keyCode, event);
    }

    private void registerHomeKeyReceiver(Context context) {
        mHomeKeyReceiver = new HomeBackReceiver();
        final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

        context.registerReceiver(mHomeKeyReceiver, homeFilter);
    }

    private void unregisterHomeKeyReceiver(Context context) {
        if (null != mHomeKeyReceiver) {
            context.unregisterReceiver(mHomeKeyReceiver);
        }
    }

    public String getCurrentPageId() {
        return currentPageId;
    }

    public void setCurrentPageId(String currentPageId) {
        this.currentPageId = currentPageId;
    }

    public abstract void dealWithUmeng();

    public abstract void dealWithVisitUmeng();
}
